import router, { asyncRoutes, constantRoutes, myAsyncRoutes, errorRoute } from '@/router'
import { queryUserMenu } from '@/api/menu'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

// 解析json路由信息
export function parseMenuRoutes(menuInfo) {
  const res = []
  if (menuInfo) {
    menuInfo.forEach(menu => {
      const obj = {
        path: menu.path,
        // menu.viewPath ? (resolve) => require([`@/views/` + menu.viewPath], resolve) : 'Layout'
        component: menu.viewPath ? resolve => require([`@/views/` + menu.viewPath], resolve) : () => import('@/layout'),
        redirect: menu.redirect,
        alwaysShow: menu.alwaysShow == '1', // will always show the root menu
        name: menu.menuName,
        meta: {
          title: menu.menuTitle,
          icon: menu.icon,
          roles: menu.roles,
          noCache: menu.noCache == '1'
        },
        children: parseMenuRoutes(menu.children)
      }
      // 无子菜单需删除 children
      if (!obj.children || obj.children.length == 0) {
        delete obj.children
      }
      res.push(obj)
    })
  }
  return res
}

// export function loadView(viewPath) {
//   return viewPath ? (resove) => require(['../views/${viewPath}.vue'], resove) : 'Layout'
// }

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      queryUserMenu().then(response => {
        const { data } = response
        accessedRoutes = parseMenuRoutes(data)
        //Object.assign(accessedRoutes, menuRoutes)
        accessedRoutes.push(errorRoute)
        //console.log(JSON.stringify(accessedRoutes))
        //Object.assign(accessedRoutes, errorRoute)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
